import type { TableType } from '@/services/api/terminalAndSim';
import type { Params } from '@/types';
import type { ProFormInstance } from '@ant-design/pro-form';
import type { SortOrder } from 'antd/lib/table/interface';
import { isEmpty } from 'lodash';
import moment from 'moment';
import dayjs from 'dayjs';
import BigNumber from 'bignumber.js';
import CryptoJS from 'crypto-js';

export type SelectOption = Partial<{
  id: string;
  label: string;
  value: string;
}>;
/* 密码AES加密 */
export const AESencode = (srcs: string) => {
  // 加密
  // "123Qwe@"    zLeML+iFBmkcyeG6DMwMnA==
  const key = '2858310341595137';
  const iv = '2890256383840258';
  // 统一将传入的字符串转成UTF8编码
  // const srcs = CryptoJS.enc.Utf8.parse(password);
  const keyHex = CryptoJS.enc.Latin1.parse(key);
  const ivHex = CryptoJS.enc.Latin1.parse(iv);
  //
  const encode = CryptoJS.AES.encrypt(srcs, keyHex, {
    iv: ivHex,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.ZeroPadding,
  });

  // console.log(encode, 'encode', encode.ciphertext.toString(CryptoJS.enc.Base64));
  const passCode = encode.ciphertext.toString(CryptoJS.enc.Base64);
  return passCode;
};

/* 计算文字长度 */

export const trunTooltip = (len: any, val: any) => {
  console.log(val);
  if (val) {
    let lens = 0; // 中文算2个字
    for (let i = 0; i < val.length; i++) {
      if (val.charCodeAt(i) >= 0 && val.charCodeAt(i) <= 255) {
        lens = lens + 1;
      } else {
        lens = lens + 2;
      }
    }

    if (lens > len) {
      return val;
    }
  }
  return ``;
};

/**
 * 获取第一个表格的可视化高度
 * @param {*} extraHeight 额外的高度(表格底部的内容高度 Number类型,默认为74)
 * @param {*} id 当前页面中有多个table时需要制定table的id
 */
export function getTableScroll(extraHeight: undefined | number = 77, id: undefined | string) {
  let tHeader = null;
  let tpagination = null;
  if (id) {
    tHeader = document.getElementById(id)
      ? // @ts-ignore
        document.getElementById(id).getElementsByClassName('ant-table-thead')[0]
      : null;
  } else {
    // eslint-disable-next-line prefer-destructuring
    tHeader = document.getElementsByClassName('ant-table-thead')[0];
    tpagination = document.querySelector('.ant-table-pagination');
  }
  // 表格内容距离顶部的距离
  let tHeaderBottom = 0;
  let tPaginationHeight = 56;
  if (tHeader) {
    tHeaderBottom = tHeader.getBoundingClientRect().bottom;
  }
  if (tpagination) {
    tPaginationHeight = 0;
  }
  // 窗体高度-表格内容顶部的高度-表格内容底部的高度
  const height = `calc(100vh - ${tHeaderBottom + extraHeight - tPaginationHeight + 36}px)`;
  return height;
}

// 这个方法比较巧妙，当初看见的时候，还赞叹了一番
export function uncamelize(str: string, separator = '_') {
  // 转换为小写
  return str.replace(/([A-Z])/g, `${separator}$1`).toLowerCase();
}

/**
 * 转换option
 * @param result 后端接口返回的数组
 * @param value 值对应的key
 * @param label label对应的key
 * @returns 返回满足于ui框架的数据格式
 */
export function transformOption(
  result: API.SysDictValueVo[] | undefined,
  value = 'value',
  label = 'label',
) {
  if (!result) {
    return [];
  }

  return (
    result &&
    result.map((item: API.SysDictValueVo) => {
      if (item && JSON.stringify(item) !== '{}') {
        return {
          label: item[label],
          value: item[value],
        };
      }
      return {};
    })
  );
}

/**
 * 转换成后端的sort
 * @param sorter table的返回的sort字段
 */
export function transformSort(sorter: Record<string, SortOrder>): string {
  const ascSort = [];
  const descSort = [];
  // eslint-disable-next-line no-restricted-syntax
  for (const [key, value] of Object.entries(sorter)) {
    if (value === 'ascend') {
      ascSort.push(uncamelize(key));
    }
    if (value === 'descend') {
      descSort.push(uncamelize(key));
    }
  }

  let result: string = '';
  if (ascSort.length) {
    result += `${ascSort.join(',')} asc,`;
  }

  if (descSort.length) {
    result += `${descSort.join(',')} desc,`;
  }

  if (result.length || result[result.length - 1] === ',') {
    result = result.substring(0, result.length - 1);
  }
  return result;
}

export function transformTableParams(
  formRef: React.MutableRefObject<ProFormInstance<Record<string, any>> | undefined>,
  params: Params,
  sorter: Record<string, SortOrder>,
  tableRef: any,
  format = 'YYYY-MM-DD',
) {
  const formValue = formRef.current?.getFieldsValue();
  const myParams: TableType = {
    ...params,
    page: params?.current,
    index: params?.current,
    limit: params.pageSize,
    ...formValue,
  };
  if (!isEmpty(sorter)) {
    myParams.sort = transformSort(sorter);
  }
  if (myParams.startDate) {
    myParams.startDate = moment(myParams.startDate).format(format);
  } else {
    delete myParams.startDate;
  }

  if (myParams.endDate) {
    myParams.endDate = moment(myParams.endDate).format(format);
  } else {
    delete myParams.endDate;
  }

  // dateRange 的支持
  // if (myParams.dateRange) {
  const key = Object.keys(myParams).find((key) => key.indexOf('dateRange') > -1);
  console.log(myParams);
  console.log(key);
  if (key && myParams[key]) {
    myParams.startDate = moment(myParams[key][0]).format(format);
    myParams.endDate = moment(myParams[key][1]).format(format);
    const timeFields = key.split('.')[1];
    let startTime, endTime;
    if (timeFields) {
      startTime = timeFields.split('-')[0];
      endTime = timeFields.split('-')[1];
      if (startTime && endTime) {
        myParams[startTime] = `${myParams.startDate} 00:00:00`;
        myParams[endTime] = `${myParams.endDate} 23:59:59`;
        delete myParams.startDate;
        delete myParams.endDate;
        delete myParams[key];
      }
    }
    delete myParams.dateRange;
  }

  if (myParams.date) {
    myParams.date = dayjs(myParams.date).format('YYYY-MM-DD');
  }
  if (myParams.xtime) {
    myParams.startTime = `${moment(myParams.xtime[0]).format(format)}`;
    myParams.endTime = `${moment(myParams.xtime[1]).format(format)}`;
    delete myParams.xtime;
  }

  if (myParams.time) {
    myParams.startTime = `${moment(myParams.time[0]).format(format)} 00:00:00`;
    myParams.endTime = `${moment(myParams.time[1]).format(format)} 23:59:59`;
    delete myParams.time;
  }

  if (myParams._time) {
    myParams.startTime = dayjs(myParams._time[0]).format('YYYY-MM-DD HH:mm:ss');
    myParams.endTime = dayjs(myParams._time[1]).format('YYYY-MM-DD HH:mm:ss');
    delete myParams._time;
  }
  return myParams;
}

export function secondsFormat(time: number) {
  const hour = Math.floor(time / 3600); // Math.floor()向下取整
  const minute = Math.floor((time - hour * 3600) / 60);
  const second = time - hour * 3600 - minute * 60;

  // eslint-disable-next-line prefer-template
  return (hour > 0 ? hour + '时' : '') + (minute > 0 ? minute + '分' : '') + second + '秒';
}

export function turnImgurlList(img: [], action: (v: any) => void = () => {}) {
  const urlList = img.map((v: any) => {
    if (v.name) {
      const item = {
        ...v,
        uid: v.id,
        //url: `${ENV_IMG_URL}${v.name}`,
        thumbUrl: `${ENV_IMG_URL}${v.name}`,
      };
      action(item);
      return item;
    }
  });
  return urlList.filter((val) => Boolean(val));
}

export const tranformMapData = (data: any) => {
  const points = data.map((v: any) => {
    return [v.x, v.y];
  });
  return points || [];
};

/* 查找树 */
// @ts-ignore
export function treeFind(tree: [], func: any) {
  // eslint-disable-next-line no-restricted-syntax
  for (const data of tree) {
    if (func(data)) return data;
    if (data.children) {
      const res = treeFind(data.children, func);
      if (res) return res;
    }
  }
  return null;
}

export function getColums(type: any = 'day', format = 'YYYY-MM-DD', num = 15) {
  const now = moment();
  const result = [now.format(format)] as string[];
  for (let i = 1; i < num; i++) {
    result.push(now.subtract(1, type).format(format));
  }
  return result.reverse();
}

export function get12Month() {
  const result = [];
  for (let i = 1; i < 13; i++) {
    result.push(i + '月');
  }
  return result;
}

export function formartNumber(num: number | string, fixed = 2) {
  const bigNumber = new BigNumber(num);
  const tenThousand = new BigNumber(10000);
  const million = new BigNumber(10000000);
  if (bigNumber.isGreaterThan(million)) {
    return {
      value: bigNumber.div(million).toFixed(fixed, 0).toString(),
      unit: '千万',
    };
  } else if (bigNumber.isGreaterThan(tenThousand)) {
    return {
      value: bigNumber.div(tenThousand).toFixed(fixed, 0).toString(),
      unit: '万',
    };
  } else {
    return {
      value: bigNumber.toString(),
      unit: null,
    };
  }
}

// 如有值，则显示值，无值，则显示‘-’
export const displayVal = (val: string | number) =>
  val === null || val === undefined || Number.isNaN(NaN) ? '-' : val;

// 去最后两位数
export const doubleDigit = (val: number) => (val ? val.toFixed(2) : '-');
